package config

import (
	"common/helper"
	"database/sql"
	"sort"
	"strconv"
)

/*
打码配置
*/

type CfgFakeGameItem struct {
	Id         int    `json:"id" db:"id"`
	GameType   string `json:"game" db:"game"`                 //“PG”,"PP"
	GameId     string `json:"game_id" db:"game_id"`           // 真游戏ID
	FakeGameId string `json:"fake_game_id" db:"fake_game_id"` //假游戏ID
	Status     int    `json:"status" db:"status"`
	GameName   string `json:"game_name" db:"game_name"`
	PlatformId string `json:"platform_id" db:"platform_id"`
}
type FakeGameCfg struct {
}

var cfgFakeGameList []CfgFakeGameItem

func FakeGameCfgSetRow(rows *sql.Rows) {
	var tVal CfgFakeGameItem
	var err error
	err = rows.Scan(&tVal.GameType, &tVal.GameId, &tVal.FakeGameId, &tVal.Status, &tVal.GameName, &tVal.PlatformId)
	if err != nil {
		helper.InfoLog("FakePgCfgSetRow,scan err")
		return
	}

	cfgFakeGameList = append(cfgFakeGameList, tVal)
	platId, _ := strconv.Atoi(tVal.PlatformId)
	G_GameType[platId/10*10] = "1"
	G_GameType[platId] = "1"
}

func FakeGameCfgRemove() {
	cfgFakeGameList = []CfgFakeGameItem{}
}

/*
根据线路优先级 查找真PG对应的假PG
*/
func GetFakeGamePlatformByPrior(GameType string, GameId string, tester string) (string, string, bool) {
	allRoute := GetFakeGameAllRoute(GameType)
	if tester == "2" {
		sort.Slice(allRoute, func(i, j int) bool {
			return allRoute[i].Test < allRoute[j].Test
		})
	} else {
		sort.Slice(allRoute, func(i, j int) bool {
			return allRoute[i].Priority < allRoute[j].Priority
		})
	}

	for _, RouteItem := range allRoute {
		if RouteItem.status == 0 && tester != "2" {
			continue
		}

		if tester == "2" && RouteItem.Test == 0 {
			continue
		}

		helper.InfoLog("RouteItem:%s", RouteItem.PlatformId)
		helper.InfoLog("GameType:%s", GameType)
		helper.InfoLog("GameId:%s", GameId)
		helper.InfoLog("cfgFakeGameList:%d", len(cfgFakeGameList))
		for _, FakePgItem := range cfgFakeGameList {
			if RouteItem.PlatformId == FakePgItem.PlatformId &&
				FakePgItem.GameId == GameId &&
				FakePgItem.FakeGameId != "0" &&
				FakePgItem.GameType == GameType &&
				FakePgItem.Status == 1 {
				return FakePgItem.PlatformId, FakePgItem.FakeGameId, true
			}
		}
	}

	return "0", "0", false
}
func GetRealGameStatus(pgGameId string, gameType string) int {
	gameTypeInt, _ := strconv.Atoi(gameType)
	return IsSwitchToFake(pgGameId, gameTypeInt)
}

func FindFakePlatByFakeId(gameId string) string {
	for _, value := range cfgFakeGameList {
		if value.FakeGameId == gameId {
			return value.PlatformId
		}
	}
	return "0"
}
